#include "TinyXmlWrapper.h"
#include <sstream>
#include <string.h> //_strcmpi

bool TinyXmlWrapper::readAttribute(const TiXmlElement *element, const char *name, std::int32_t &value)
{
    const char *s = element->Attribute(name);

    if (s == nullptr)
    {
        return false;
    }

    value = (std::int32_t)atol(s);
    
    return true;

}

bool TinyXmlWrapper::readAttribute(const TiXmlElement *element, const char *name, std::uint32_t &value)
{
    const char *s = element->Attribute(name);

    if (s == nullptr)
    {
        return false;
    }
    value = (std::uint32_t)atol(s);
    
    return true;
}

bool TinyXmlWrapper::readAttribute(const TiXmlElement *element, const char *name, std::int16_t &value)
{
    const char *s = element->Attribute(name);

    if (s == nullptr)
    {
        return false;
    }
    
    value = (std::int16_t)atol(s);
    
    return true;
}

bool TinyXmlWrapper::readAttribute(const TiXmlElement *element, const char *name, std::uint16_t &value)
{
    const char *s = element->Attribute(name);

    if (s == nullptr)
    {
        return false;
    }

    value = (std::uint16_t)atol(s);
    
    return true;
}

bool TinyXmlWrapper::readAttribute(const TiXmlElement *element, const char *name, bool &value)
{
    const char *s = element->Attribute(name);

    if (s == nullptr)
    {
        return false;
    }

    value = strcmp("true", s) == 0;
    
    return true;
}

bool TinyXmlWrapper::readAttribute(const TiXmlElement *element, const char *name, std::string &value)
{
    const char *s = element->Attribute(name);

    if (s == nullptr)
    {
        return false;
    }

    value = s;

    return true;
}

void TinyXmlWrapper::writeAttribute(TiXmlElement *element, const char *name, std::int32_t value)
{
    std::stringstream ss;
    ss << value;
    element->SetAttribute(name, ss.str().c_str());
}

void TinyXmlWrapper::writeAttribute(TiXmlElement *element, const char *name, std::uint32_t value)
{
    std::stringstream ss;
    ss << value;
    element->SetAttribute(name, ss.str().c_str());
}

void TinyXmlWrapper::writeAttribute(TiXmlElement *element, const char *name, std::int16_t value)
{
    std::stringstream ss;
    ss << value;
    element->SetAttribute(name, ss.str().c_str());
}

void TinyXmlWrapper::writeAttribute(TiXmlElement *element, const char *name, std::uint16_t value)
{
    std::stringstream ss;
    ss << value;
    element->SetAttribute(name, ss.str().c_str());
}

void TinyXmlWrapper::writeAttribute(TiXmlElement *element, const char *name, bool value)
{
    if (value)
    {
        element->SetAttribute(name, "true");
    }
    else
    {
        element->SetAttribute(name, "false");
    }
}

void TinyXmlWrapper::writeAttribute(TiXmlElement *element, const char *name, const std::string &value)
{
    element->SetAttribute(name, value.c_str());
}
